import Axios from 'axios'
import fs from 'fs'
import path from 'path'
import ora from 'ora'
import  zipper from 'zip-local'
import  chalk from 'chalk'
import  FormData from 'form-data'
// const inquirer = require('inquirer')

import CONFIG from "./src/config.mjs";
const errorLog = (error) => console.log(chalk.red(`---------------> ${error}`))
const defaultLog = (log) => console.log(chalk.blue(`---------------> ${log}`))
const successLog = (log) => console.log(chalk.green(`---------------> ${log}`))
defaultLog(`当前请求地址：${CONFIG.LOCATION_ORIGIN}...`)
// 文件夹位置
const distDir = path.resolve(process.cwd(), './src/static')
const distZipPath = path.resolve(process.cwd(), `./static${CONFIG.VERSION_NUMBER}.zip`)

// ********* static 文件夹 *********
const zipDist = async () => {
  // 上传文件
  const spinner = ora('准备压缩文件').start()
  try {
    if (fs.existsSync(distZipPath)) {
      defaultLog('static.zip已经存在, 即将删除压缩包')
      fs.unlinkSync(distZipPath)
    } else {
      defaultLog('即将开始压缩zip文件')
    }
    await zipper.sync.zip(distDir).compress().save(distZipPath)
    successLog('文件夹压缩成功')
  } catch (error) {
    errorLog(error)
    errorLog('压缩dist文件夹失败')
  } finally {
    spinner.stop()
  }
}

// ********* 上传到指定服务器 *********
const uploadZipByHttp = async () => {
  const formData = new FormData()
  formData.append('file', fs.createReadStream(distZipPath))

  const headers = formData.getHeaders() // 获取headers

  // 上传文件
  const spinner = ora('准备上传文件').start()

  // 获取form-data长度
  formData.getLength(async (err, length) => {
    headers['content-length'] = length
    try {
      const res = await Axios.request({
        method: 'POST',
        url: `${CONFIG.LOCATION_ORIGIN}/customer/common/image/uploadZip?prefix=${CONFIG.WECHAT_APPID+CONFIG.VERSION_NUMBER}`,
        headers,
        data: formData,
        timeout: 20 * 60 * 1000,
        maxBodyLength: Infinity
      })
      defaultLog(res.data)
      if (res.status === 200 && res.data?.code === 200) {
        successLog('上传成功..')
      } else {
        errorLog(res.data?.msg || '未知错误')
        errorLog('上传失败')
      }
    } catch (error) {
      errorLog(error)
      errorLog('上传失败')
    } finally {
      spinner.stop()
    }
  })
}

// 执行打包上传命令
async function runTask() {
  await zipDist()
  await uploadZipByHttp()
}

// inquirer
//   .prompt([
//     {
//       type: 'confirm',
//       name: 'hasBuild',
//       message: '是否进行图片上传？'
//     }
//   ])
//   .then((answers) => {
//     const hasBuild = !!answers.hasBuild
//     hasBuild && runTask()
//   })
runTask()
